//
//  XMMyOrderViewController.m
//  XMJJ_zml
//
//  Created by 丁浩 on 2025/5/26.
//

#import "XMMyOrderViewController.h"
#import "XMMyOrderView.h"
#import "XMNetwork+mine.h"
#import "XMNetwork+home.h"
#import "XMMyOrderModel.h"
#import "XMWaitPayOrderDetailViewController.h"
#import "XMWaitMeetOrderViewController.h"
#import "XMOrderMeetingViewController.h"
#import "XMReturnDetailInfoViewController.h"
#import "XMOrderResellDetailViewController.h"
#import "XMPayViewController.h"
#import "XMQRCodeViewController.h"
#import "XMConfirmOrderViewController.h"

#import "XMFriendListViewController.h"

#import "XMApplyForReturnViewController.h"
#import "XMMeetEvaluateViewController.h"
#import "XMOrderDetailModel.h"
#import "XMRefuseRefundReasonView.h"

@interface XMMyOrderViewController ()<XMMyOrderViewDelegate>

@property (nonatomic, strong) XMMyOrderView *myOrderView;

@property (nonatomic, strong) UITextField *priceTextField;

@property (nonatomic, copy) NSString *statusStr;
@property (nonatomic, copy) NSString *buyOrShow;
@property (nonatomic, assign) NSInteger page;

@end

@implementation XMMyOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self creatUI];
}

- (void)creatUI {
    [self.view addSubview:self.myOrderView];
    _statusStr = @"0";
    _buyOrShow = @"1";
    [self getMyOrderList];
}

//我的订单列表
- (void)getMyOrderList {
    XMWeakSelf;
    [_Network getMyOrderListWithStatus:_statusStr
                               pageNum:[NSString stringWithFormat:@"%ld", _page]
                             buyOrShow:_buyOrShow
                               success:^(id  _Nonnull responseObject) {
        NSArray *orderModelArr = [NSArray yy_modelArrayWithClass:[XMMyOrderModel class] json:responseObject[@"data"]];
        [weakSelf.myOrderView setContentWithOrderList:orderModelArr
                                            buyOrShow:weakSelf.buyOrShow
                                                 page:weakSelf.page];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//获取转卖信息
- (void)getResellInfoWithOrderModel:(XMMyOrderModel *)orderModel {
//                           price:(NSString *)price {
    XMWeakSelf;
    [_Network getResellInfoWithOrderId:orderModel.orderId
                                 money:orderModel.price
                               success:^(id  _Nonnull responseObject) {
        XMUserModel *userModel = [[XMUserManager shareInstance] getUser];
        NSString *giveInfoStr = [responseObject safeStringForKey:@"data"];
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters safe_setObject:giveInfoStr forKey:@"giveInfo"];
        [parameters safe_setObject:orderModel.price forKey:@"price"];
        [parameters safe_setObject:orderModel.address forKey:@"address"];
        [parameters safe_setObject:orderModel.serviceTime forKey:@"time"];
        [parameters safe_setObject:orderModel.coverImageUrl forKey:@"coverImg"];
        [parameters safe_setObject:orderModel.title forKey:@"title"];
        [parameters safe_setObject:self.priceTextField.text forKey:@"payPrice"];
        [parameters safe_setObject:@"1" forKey:@"orderType"];
        [parameters safe_setObject:userModel.nickname forKey:@"nickName"];
        [parameters safe_setObject:orderModel.serviceId forKey:@"serviceId"];
        [parameters safe_setObject:userModel.avatar forKey:@"avatar"];
        XMFriendListViewController *friendListVC = [[XMFriendListViewController alloc] init];
        friendListVC.meetDic = parameters;
        [weakSelf.navigationController pushViewController:friendListVC animated:YES];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//转卖
- (void)resellWithOrderModel:(XMMyOrderModel *)orderModel {
    XMWeakSelf;
    UIAlertController *alertVC = [UIAlertController initwithTitle:@"转卖价格" message:@"" titles:@[@"确认"] cancelTitle:@"取消" alertStyle:UIAlertControllerStyleAlert itemSelect:^(NSInteger selectIndex) {
        [weakSelf getResellInfoWithOrderModel:orderModel];
//        [weakSelf getResellInfoWithOrderId:orderModel.orderId
//                                     price:weakSelf.priceTextField.text];
    }];
    [alertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入转卖价格";
        textField.font = KFontSize(14.0);
        textField.textColor = kColorHEX(0x333333);
        weakSelf.priceTextField = textField;
    }];
    [self presentViewController:alertVC animated:YES completion:nil];
}

//赠送
- (void)giveWithOrderModel:(XMMyOrderModel *)orderModel {
    XMUserModel *userModel = [[XMUserManager shareInstance] getUser];
//    NSString *giveInfoStr = [responseObject safeStringForKey:@"data"];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
//    [parameters safe_setObject:giveInfoStr forKey:@"giveInfo"];
    [parameters safe_setObject:orderModel.price forKey:@"price"];
    [parameters safe_setObject:orderModel.address forKey:@"address"];
    [parameters safe_setObject:orderModel.serviceTime forKey:@"time"];
    [parameters safe_setObject:orderModel.coverImageUrl forKey:@"coverImg"];
    [parameters safe_setObject:orderModel.title forKey:@"title"];
    [parameters safe_setObject:userModel.nickname forKey:@"nickName"];
    [parameters safe_setObject:@"2" forKey:@"orderType"];
    [parameters safe_setObject:orderModel.serviceId forKey:@"serviceId"];
    [parameters safe_setObject:userModel.avatar forKey:@"avatar"];
    XMFriendListViewController *friendListVC = [[XMFriendListViewController alloc] init];
    friendListVC.meetDic = parameters;
    [self.navigationController pushViewController:friendListVC animated:YES];
//    XMWeakSelf;
//    [_Network getGiveInfoWithOrderId:orderModel.orderId
//                             success:^(id  _Nonnull responseObject) {
//        XMUserModel *userModel = [[XMUserManager shareInstance] getUser];
//        NSString *giveInfoStr = [responseObject safeStringForKey:@"data"];
//        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
//        [parameters safe_setObject:giveInfoStr forKey:@"giveInfo"];
//        [parameters safe_setObject:orderModel.price forKey:@"price"];
//        [parameters safe_setObject:orderModel.address forKey:@"address"];
//        [parameters safe_setObject:orderModel.serviceTime forKey:@"time"];
//        [parameters safe_setObject:orderModel.coverImageUrl forKey:@"coverImg"];
//        [parameters safe_setObject:orderModel.title forKey:@"title"];
//        [parameters safe_setObject:userModel.nickname forKey:@"nickName"];
//        [parameters safe_setObject:@"2" forKey:@"orderType"];
//        [parameters safe_setObject:orderModel.serviceId forKey:@"serviceId"];
//        [parameters safe_setObject:userModel.avatar forKey:@"avatar"];
//        XMFriendListViewController *friendListVC = [[XMFriendListViewController alloc] init];
//        friendListVC.meetDic = parameters;
//        [weakSelf.navigationController pushViewController:friendListVC animated:YES];
//    } failure:^(NSError * _Nonnull error) {
//
//    }];
}

//取消订单
- (void)cancelOrderWithOrderId:(NSString *)orderId {
    XMWeakSelf;
    [_Network cancelMeetWithOrderId:orderId
                            success:^(id  _Nonnull responseObject) {
        [weakSelf refreshData];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//立即付款
- (void)payOrderWithOrderId:(NSString *)orderId
                      price:(NSString *)priceStr {
    XMPayViewController *payVC = [[XMPayViewController alloc] init];
    payVC.orderId = orderId;
    payVC.priceStr = priceStr;
    [self.navigationController pushViewController:payVC animated:YES];
}

//退款详情
- (void)checkRefundDetailWithOrderId:(NSString *)orderId {
    XMReturnDetailInfoViewController *returnDetailInfoVC = [[XMReturnDetailInfoViewController alloc] init];
    [self.navigationController pushViewController:returnDetailInfoVC animated:YES];
}

//删除订单
- (void)orderDeleteWithOrderId:(NSString *)orderId {
    XMWeakSelf;
    [_Network deleteOverMeetingWithOrderId:orderId
                                   success:^(id  _Nonnull responseObject) {
        [weakSelf refreshData];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//重新下单
- (void)reOrderWithServiceId:(NSString *)serviceId {
    XMWeakSelf;
    [_Network getMeetDetailWithServiceId:serviceId
                                 success:^(id  _Nonnull responseObject) {
        XMMeetDetailModel *detailModel = [XMMeetDetailModel yy_modelWithJSON:responseObject[@"data"]];
        XMConfirmOrderViewController *confirmOrderVC = [[XMConfirmOrderViewController alloc] init];
        confirmOrderVC.meetDetailModelArr = @[detailModel];
        [weakSelf.navigationController pushViewController:confirmOrderVC animated:YES];
    } failure:^(NSError * _Nonnull error) {
        
    }];
//    [_Network meetingReputawayWithServiceId:<#(nonnull NSString *)#> success:<#^(id  _Nonnull responseObject)successBlock#> failure:<#^(NSError * _Nonnull error)failureBlock#>]
}

//申请退款
- (void)applyForRefundWithOrderId:(NSString *)orderId {
    XMWeakSelf;
    [_Network getOrderDetailWithOrderId:orderId
                                success:^(id  _Nonnull responseObject) {
        XMOrderDetailModel *orderDetailModel = [XMOrderDetailModel yy_modelWithJSON:responseObject[@"data"]];
        XMApplyForReturnViewController *applyForReturnVC = [[XMApplyForReturnViewController alloc] init];
        applyForReturnVC.orderDetailModel = orderDetailModel;
        [weakSelf.navigationController pushViewController:applyForReturnVC animated:YES];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//确认结束
- (void)confirmOverWithOrderId:(NSString *)orderNo {
    XMWeakSelf;
    [_Network meetOverWithOrderNo:orderNo
                          success:^(id  _Nonnull responseObject) {
        [weakSelf refreshData];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//去评价
- (void)goEvaluateWithOrderId:(NSString *)orderId {
    XMWeakSelf;
    [_Network getOrderDetailWithOrderId:orderId
                                success:^(id  _Nonnull responseObject) {
        XMOrderDetailModel *orderDetailModel = [XMOrderDetailModel yy_modelWithJSON:responseObject[@"data"]];
        XMMeetEvaluateViewController *evaluateVC = [[XMMeetEvaluateViewController alloc] init];
        evaluateVC.orderDetailModel = orderDetailModel;
        [weakSelf.navigationController pushViewController:evaluateVC animated:YES];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

//通过/拒绝退款
- (void)refuseRefundWithRefundId:(NSString *)refundId
                          accept:(NSString *)acceptStr {
    if ([acceptStr isEqualToString:@"false"]) {
        XMRefuseRefundReasonView *refuseRefundView = [[XMRefuseRefundReasonView alloc] initWithFrame:self.view.bounds];
        [self.view addSubview:refuseRefundView];
        [refuseRefundView show];
        XMWeakSelf;
        refuseRefundView.confirmBlock = ^(NSString * _Nonnull reasonStr) {
            [_Network dealwithRefundWithRefundId:refundId
                                          accept:acceptStr
                                          reason:reasonStr
                                         success:^(id  _Nonnull responseObject) {
                [MBProgressHUD showSuccess:@"提交成功"];
                [weakSelf refreshData];
            } failure:^(NSError * _Nonnull error) {
                
            }];
        };
    }
    else {
        XMWeakSelf;
        [_Network dealwithRefundWithRefundId:refundId
                                      accept:acceptStr
                                      reason:@""
                                     success:^(id  _Nonnull responseObject) {
            [MBProgressHUD showSuccess:@"提交成功"];
            [weakSelf refreshData];
        } failure:^(NSError * _Nonnull error) {
            
        }];
    }
}

//取消退款
- (void)cancelRefundWithRefundId:(NSString *)refundId {
    XMWeakSelf;
    [_Network cancelRefundWithRefundId:refundId
                               success:^(id  _Nonnull responseObject) {
        [weakSelf refreshData];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - Delegate

- (void)topTabSelect:(NSString *)selectStr {
    _buyOrShow = selectStr;
    _page = 1;
    [self getMyOrderList];
}

- (void)statusSelectIndex:(NSString *)selectStr {
    _statusStr = selectStr;
    _page = 1;
    [self getMyOrderList];
}

- (void)refreshData {
    _page = 1;
    [self getMyOrderList];
}

- (void)loadMore {
    _page += 1;
    [self getMyOrderList];
}

//功能项
- (void)funcActionWithPosiType:(NSInteger)posiType
                    orderModel:(nonnull NSArray *)orderModelArr {
//                   orderStatus:(NSString *)orderStatus
//                       orderId:(nonnull NSString *)orderId
//                    orderOrgId:(NSString *)orderOrgId
//                     serviceId:(nonnull NSString *)serviceId
//                      refundId:(nonnull NSString *)refundId
//                         price:(nonnull NSString *)priceStr {
    XMMyOrderModel *orderModel = [orderModelArr firstObject];
    if ([_buyOrShow isEqualToString:@"1"]) {
        switch (posiType) {
            case 1: {
                if ([orderModel.status isEqualToString:@"20"]) {
//                    [self resellWithOrderId:orderModel.orderId]; //转卖
                    [self resellWithOrderModel:orderModel]; //转卖
                }
            }
                break;
                
            case 2: {
                switch ([orderModel.status integerValue]) {
                    case 10: {
                        [self cancelOrderWithOrderId:orderModel.orderOrgId];  //取消订单
                    }
                        break;
                    case 12: case 13: case 14: case 18: case 19: case 40: {
                        [self orderDeleteWithOrderId:orderModel.orderId]; //删除订单
                    }
                        break;
                    case 20: {
                        [self giveWithOrderModel:orderModel]; //赠送
                    }
                        break;
                    case 50: {
                        [self checkRefundDetailWithOrderId:orderModel.orderId]; //退款详情
                    }
                        
                    default:
                        break;
                }
            }
                break;
            case 3: {
                switch ([orderModel.status integerValue]) {
                    case 10: {
                        [self payOrderWithOrderId:orderModel.orderOrgId price:orderModel.price]; //去支付
                    }
                        break;
                    case 11: case 12: case 17: case 18: case 19: {
                        [self checkRefundDetailWithOrderId:orderModel.refundId]; //退款详情
                    }
                        break;
                    case 13: case 14: {
                        [self reOrderWithServiceId:orderModel.serviceId]; //重新下单
                    }
                        break;
                    case 20: {
                        [self applyForRefundWithOrderId:orderModel.orderId]; //申请退款
                    }
                        break;
                    case 30: {
                        [self confirmOverWithOrderId:orderModel.orderId]; //确认结束
                    }
                        break;
                    case 40: {
                        [self goEvaluateWithOrderId:orderModel.orderId]; //去评价
                    }
                        break;
                    case 50: {
                        [self cancelRefundWithRefundId:orderModel.refundId]; //取消退款
                    }
                        break;
                        
                    default:
                        break;
                }
            }
                break;
                
            default:
                break;
        }
    }
    else {
        switch (posiType) {
            case 1: {
                if ([orderModel.status isEqualToString:@"12"] || [orderModel.status isEqualToString:@"19"]) {
                    [self orderDeleteWithOrderId:orderModel.orderId];
                }
                else {
                    [self refuseRefundWithRefundId:orderModel.refundId accept:@"false"];
                }
            }
                break;
            case 2: {
                switch ([orderModel.status integerValue]) {
                    case 10: {
                        [self cancelOrderWithOrderId:orderModel.orderId];
                    }
                        break;
                    case 20: { //待见面 扫码核验
                        XMQRCodeViewController *qrcodeVC = [[XMQRCodeViewController alloc] init];
                        [self.navigationController pushViewController:qrcodeVC animated:YES];
                    }
                        break;
                    case 11:case 17: {
                        [self refuseRefundWithRefundId:orderModel.refundId accept:@"true"];
                    }
                        break;
                    case 30: {
                        //联系对方
                    }
                        break;
                    case 18:case 19:case 21: {
                        XMReturnDetailInfoViewController *refundDetailVC = [[XMReturnDetailInfoViewController alloc] init];
                        refundDetailVC.refundId = orderModel.refundId;
                        [self.navigationController pushViewController:refundDetailVC animated:YES];
                    }
                        break;
                        
                    default:
                        break;
                }
            }
                
            default:
                break;
        }
    }
}

//状态 0全部，10等付款，20待见面，30见面中，40待评价，50退款售后 状态10等付数，20待见面，30见面中，40见面结束，11提出退款，12退款成功，13超时己关闭，14取消己关闭，15转卖,16赠送，17退款中，18退款审核通过，19退款成功，21拒绝退款
//查看详情
- (void)chatOrderDetailWithOrderId:(NSString *)orderId
                       orderStatus:(NSString *)orderStatus {
//    orderStatus = @"20";
    if ([_buyOrShow isEqualToString:@"1"]) {
        XMWeakSelf;
        switch ([orderStatus intValue]) {
            case 10: {  //待支付
                XMWaitPayOrderDetailViewController *orderDetailVC = [[XMWaitPayOrderDetailViewController alloc] init];
                orderDetailVC.orderId = orderId;
                [self.navigationController pushViewController:orderDetailVC animated:YES];
                orderDetailVC.editSuccessBlock = ^{
                    [weakSelf refreshData];
                };
            }
                break;
            case 11: {
                
            }
                break;
            case 13: {  //超时已关闭
                XMOrderResellDetailViewController *resellDetailVC = [[XMOrderResellDetailViewController alloc] init];
                resellDetailVC.orderId = orderId;
                resellDetailVC.meetTypeStr = @"0";
                [self.navigationController pushViewController:resellDetailVC animated:YES];
            }
                break;
            case 14: { //主动取消已关闭
                XMOrderResellDetailViewController *resellDetailVC = [[XMOrderResellDetailViewController alloc] init];
                resellDetailVC.orderId = orderId;
                resellDetailVC.meetTypeStr = @"1";
                [self.navigationController pushViewController:resellDetailVC animated:YES];
            }
                break;
            case 15: {   //转卖
                XMOrderResellDetailViewController *resellDetailVC = [[XMOrderResellDetailViewController alloc] init];
                resellDetailVC.orderId = orderId;
                resellDetailVC.meetTypeStr = @"2";
                [self.navigationController pushViewController:resellDetailVC animated:YES];
            }
                break;
            case 16: {    //转赠
                XMOrderResellDetailViewController *resellDetailVC = [[XMOrderResellDetailViewController alloc] init];
                resellDetailVC.orderId = orderId;
                resellDetailVC.meetTypeStr = @"3";
                [self.navigationController pushViewController:resellDetailVC animated:YES];
            }
                break;
            case 20: {  //待见面
                XMWaitMeetOrderViewController *meetOrderVC = [[XMWaitMeetOrderViewController alloc] init];
                meetOrderVC.orderId = orderId;
                [self.navigationController pushViewController:meetOrderVC animated:YES];
                meetOrderVC.editSuccessBlock = ^{
                    [weakSelf refreshData];
                };
            }
                break;
            case 30: {  //见面中
                XMOrderMeetingViewController *meetingVC = [[XMOrderMeetingViewController alloc] init];
                meetingVC.orderId = orderId;
                meetingVC.meetingType = @"0";
                [self.navigationController pushViewController:meetingVC animated:YES];
                meetingVC.meetEditBlock = ^{
                    [weakSelf refreshData];
                };
            }
                return;
            case 40: { //见面结束
                XMOrderMeetingViewController *meetingVC = [[XMOrderMeetingViewController alloc] init];
                meetingVC.orderId = orderId;
                meetingVC.meetingType = @"1";
                [self.navigationController pushViewController:meetingVC animated:YES];
                XMWeakSelf;
                meetingVC.meetEditBlock = ^{
                    [weakSelf refreshData];
                };
            }
            default:
                break;
        }
    }
    else {
        switch ([orderStatus intValue]) {
            case 10: {
                
            }
                break;
            case 11: {
                
            }
                break;
            case 13: {
                
            }
                break;
            case 14: {
                
            }
                break;
            case 15: {
                
            }
                break;
                
            default:
                break;
        }
    }
}

#pragma mark - Init
- (XMMyOrderView *)myOrderView {
    if (!_myOrderView) {
        _myOrderView = [[XMMyOrderView alloc] initWithFrame:self.view.bounds];
        _myOrderView.delegate = self;
    }
    return _myOrderView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
